using System;
using System.Collections.Generic;
using System.Web.Mvc;
using Netkk.Common;
using Netkk.Common.Interfaces.Services;
using Netkk.Core;
using Netkk.Core.ActionResults;
using Netkk.Common.Models;
using Netkk.Core.Auth;
using Netkk.Models;

namespace Netkk.Controllers
{
    public class DownloadController : BaseControler
    {
        private readonly IDownloadService downloadService;
        private readonly IUploadService uploadService;

        public DownloadController(IDownloadService downloadService, IUploadService uploadService)
        {
            this.downloadService = downloadService;
            this.uploadService = uploadService;
        }

        [IsAuthenticated]
        public ActionResult Index(int? id)
        {
            IEnumerable<Download> downloads = downloadService.GetAllDownloads();

            DownloadListModel model = LoadPagedDownloadsList(id ?? 1, downloads);

            return View(model);
        }

        private DownloadListModel LoadPagedDownloadsList(int id, IEnumerable<Download> downloads)
        {
            int totalPages;
            int currentPage = id == 0 ? 1 : id;

            downloads = downloads.PagedItems(10, currentPage - 1, out totalPages);

            List<DownloadModel> downloadModels = new List<DownloadModel>();

            bool allowEditOrAdd = this.IsInRole(Roles.Admin);

            downloads.ForEach(d => downloadModels.Add(DownloadModel.Create(d, allowEditOrAdd)));

            DownloadListModel model = new DownloadListModel
            {
                Downloads = downloadModels,
                TotalPages = totalPages,
                CurrentPage = currentPage,
                ShowCreateDownload = allowEditOrAdd
            };

            return model;
        }

        [IsAuthenticated]
        public ActionResult Download(Guid id)
        {
            Download download = downloadService.GetDownloadById(id);
            return new DownloadResult { Download = download };
        }

        [IsAuthenticated]
        [UserInRole(Roles.Admin)]
        public ActionResult Create()
        {
            return View(DownloadModel.Create());
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [UserInRole(Roles.Admin)]
        public ActionResult Create(FormCollection collection)
        {
            DownloadModel model = DownloadModel.Create();
            try
            {
                UpdateModel(model, new[] { "Name", "Description" });

                if (uploadService.DoUpload("NewFile"))
                {
                    model.FileName = uploadService.UploadedFile.FileName;
                    model.ContentType = uploadService.UploadedFile.MimeType;
                    model.ContentSize = uploadService.UploadedFile.FileSize;
                }
                else
                {
                    if (uploadService.UploadError.Code != 0)
                    {
                        ModelState.AddModelError("ImageFile", "Es ist ein Fehler passiert. " + uploadService.UploadError.Message);
                        return View(model);
                    }
                }

                Download download = model.MapToDownload();
                if (!downloadService.SaveDownload(download))
                {
                    return View(model);
                }

                return RedirectToAction("Index");
            }
            catch
            {
                return View(model);
            }
        }

        [UserInRole(Roles.Admin)]
        public ActionResult Edit(Guid id)
        {
            Download download = downloadService.GetDownloadById(id);

            DownloadModel model = DownloadModel.Create(download);

            return View(model);
        }

        [UserInRole(Roles.Admin)]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(Guid id, FormCollection collection)
        {
            Download download = downloadService.GetDownloadById(id);

            DownloadModel model = DownloadModel.Create(download);

            try
            {
                UpdateModel(model, new[] { "Name", "Description" });

                if (uploadService.DoUpload("NewFile"))
                {
                    model.FileName = uploadService.UploadedFile.FileName;
                    model.ContentType = uploadService.UploadedFile.MimeType;
                    model.ContentSize = uploadService.UploadedFile.FileSize;
                }
                else
                {
                    if (uploadService.UploadError.Code != 0)
                    {
                        ModelState.AddModelError("ImageFile", "Es ist ein Fehler passiert. " + uploadService.UploadError.Message);
                        return View(model);
                    }
                }

                download = model.MapToDownload();
                if (!downloadService.SaveDownload(download))
                {
                    return View(model);
                }

                return RedirectToAction("Index");
            }
            catch
            {
                return View(model);
            }
        }

        [UserInRole(Roles.Admin)]
        public ActionResult Delete(Guid id)
        {
            Download download = downloadService.GetDownloadById(id);
            downloadService.DeleteDownload(download);

            return RedirectToAction("Index");

        }
    }
}
